package com.cordova.test.imageselect

import android.annotation.SuppressLint
import android.app.Activity
import android.database.Cursor
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.provider.MediaStore
import android.support.v4.app.FragmentActivity
import android.support.v4.app.LoaderManager
import android.support.v4.content.CursorLoader
import android.support.v4.content.Loader
import com.cordova.test.imageselect.module.ImageFolder
import com.cordova.test.imageselect.module.ImageItem
import java.io.File
import java.util.ArrayList

@SuppressLint("ParcelCreator")
class LoadImageResource() : LoaderManager.LoaderCallbacks<Cursor> {

    private val LOADER_ALL = 0         //加载所有图片
    private val LOADER_CATEGORY = 1    //分类加载图片
    private val IMAGE_PROJECTION = arrayOf(//查询图片需要的数据列
            MediaStore.Images.Media.DISPLAY_NAME, //图片的显示名称  aaa.jpg
            MediaStore.Images.Media.DATA, //图片的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
            MediaStore.Images.Media.SIZE, //图片的大小，long型  132492
            MediaStore.Images.Media.WIDTH, //图片的宽度，int型  1920
            MediaStore.Images.Media.HEIGHT, //图片的高度，int型  1080
            MediaStore.Images.Media.MIME_TYPE, //图片的类型     image/jpeg
            MediaStore.Images.Media.DATE_ADDED)    //图片被添加的时间，long型  1450518608

    private var activity: FragmentActivity? = null
    private var loadedListener: OnImagesLoadedListener? = null    //图片加载完成的回调接口
    private val imageFolders = ArrayList<ImageFolder>()   //所有的图片文件夹

    constructor(activity: FragmentActivity, path: String?, loadedListener: OnImagesLoadedListener) : this() {
        this.activity = activity
        this.loadedListener = loadedListener
        var loaderManager: LoaderManager = activity.supportLoaderManager
        if (path == null) {
            loaderManager.initLoader(LOADER_ALL, null, this)//加载所有的图片
        } else {
            //加载指定目录的图片
            val bundle = Bundle()
            bundle.putString("path", path)
            loaderManager.initLoader(LOADER_CATEGORY, bundle, this)
        }
    }

    override fun onCreateLoader(p0: Int, p1: Bundle?): Loader<Cursor> {
        var cursorLoader: CursorLoader? = null
        //扫描所有图片
        if (p0 == LOADER_ALL)
            cursorLoader = CursorLoader(activity!!, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, null, null, IMAGE_PROJECTION[6] + " DESC")
        //扫描某个图片文件夹
        if (p0 == LOADER_CATEGORY)
            cursorLoader = CursorLoader(activity!!, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, IMAGE_PROJECTION[1] + " like '%" + p1?.getString("path") + "%'", null, IMAGE_PROJECTION[6] + " DESC")

        return cursorLoader!!
    }

    override fun onLoadFinished(p0: Loader<Cursor>, p1: Cursor?) {
        imageFolders.clear()
        if (p1 != null) {
            val allImages: ArrayList<ImageItem> = ArrayList()
            while (p1.moveToNext()) {
                val imageName: String = p1.getString(p1.getColumnIndexOrThrow(IMAGE_PROJECTION[0]))
                val imagePath: String = p1.getString(p1.getColumnIndexOrThrow(IMAGE_PROJECTION[1]))
                val file = File(imagePath)
                if (!file.exists() || file.length() <= 0) {
                    continue
                }
                var imageSize: Long = p1.getLong(p1.getColumnIndexOrThrow(IMAGE_PROJECTION[2]))
                var imageWidth: Int = p1.getInt(p1.getColumnIndexOrThrow(IMAGE_PROJECTION[3]))
                val imageHeight = p1.getInt(p1.getColumnIndexOrThrow(IMAGE_PROJECTION[4]))
                val imageMimeType = p1.getString(p1.getColumnIndexOrThrow(IMAGE_PROJECTION[5]))
                val imageAddTime = p1.getLong(p1.getColumnIndexOrThrow(IMAGE_PROJECTION[6]))
                //封装实体
                val imageItem = ImageItem()
                imageItem.name = imageName
                imageItem.path = imagePath
                imageItem.size = imageSize
                imageItem.width = imageWidth
                imageItem.height = imageHeight
                imageItem.mimeType = imageMimeType
                imageItem.addTime = imageAddTime
                allImages.add(imageItem)
                //根据父路径分类存放图片
                val imageFile = File(imagePath)
                val imageParentFile = imageFile.parentFile
                val imageFolder = ImageFolder()
                imageFolder.name = imageParentFile.name
                imageFolder.path = imageParentFile.absolutePath
                if (!imageFolders.contains(imageFolder)) {
                    val images = ArrayList<ImageItem>()
                    images.add(imageItem)
                    imageFolder.cover = imageItem
                    imageFolder.images = images
                    imageFolders.add(imageFolder)
                } else {
                    imageFolders[imageFolders.indexOf(imageFolder)].images?.add(imageItem)
                }
            }
            //防止没有图片报异常
            if (p1.count > 0 && allImages.size > 0) {
                //构造所有图片的集合
                val allImagesFolder = ImageFolder()
                allImagesFolder.name = "所有图片"
                allImagesFolder.path = "/"
                allImagesFolder.cover = allImages[0]
                allImagesFolder.images = allImages
                imageFolders.add(0, allImagesFolder)  //确保第一条是所有图片
            }
        }
        loadedListener?.onImagesLoaded(imageFolders)
    }

    override fun onLoaderReset(p0: Loader<Cursor>) {

    }

    interface OnImagesLoadedListener {
        fun onImagesLoaded(imageFolders: List<ImageFolder>)
    }

//    override fun writeToParcel(parcel: Parcel, flags: Int) {
//
//    }
//
//    override fun describeContents(): Int {
//        return 0
//    }

//    companion object CREATOR : Parcelable.Creator<LoadImageResource> {
//        override fun createFromParcel(parcel: Parcel): LoadImageResource {
//            return LoadImageResource(parcel)
//        }
//
//        override fun newArray(size: Int): Array<LoadImageResource?> {
//            return arrayOfNulls(size)
//        }
//    }
}